package com.winning.pmph.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beust.jcommander.internal.Maps;
import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
import com.winning.pmph.config.ResourceServerConfig;
import com.winning.pmph.entity.IncreaseQrCode;
import com.winning.pmph.entity.IncreaseResource;
import com.winning.pmph.entity.IncreaseResourceSub;
import com.winning.pmph.entity.KnowledgeLib;
import com.winning.pmph.enumeration.KnowledgeSystem;
import com.winning.pmph.mapper.IncreaseBookMapper;
import com.winning.pmph.mapper.IncreaseQrCodeMapper;
import com.winning.pmph.mapper.IncreaseResourceMapper;
import com.winning.pmph.schedule.QuartzManager;
import com.winning.pmph.utils.ApplicationContextUtil;
import com.winning.pmph.utils.FfmpegUtil;
import com.winning.pmph.utils.HttpApi;
import com.winning.pmph.utils.PMPHAppUtil;
import com.winning.pmph.utils.PptToImg;
import com.winning.pmph.utils.ResourceServerUtils;
import com.winning.pmph.utils.RocketMQProducerUtil;
import com.winning.pmph.vo.CategorySelectVo;
import com.winning.pmph.vo.IncreaseResourceVo;
import com.winning.pmph.vo.ResourceTreeVo;
import com.winning.pmph.vo.UploadFileVo;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ZipUtil;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lbm
 * @since 2021-12-30
 */
@Service
public class IncreaseUploadService extends ServiceImpl<IncreaseResourceMapper, IncreaseResource> {
	@Autowired
	IncreaseBookMapper increaseBookMapper;
	@Autowired
	IncreaseQrCodeMapper increaseQrCodeMapper;
	@Autowired
	QuartzManager quartzManager;
	@Autowired
	KnowledgeSyncStatusService knowledgeSyncStatusService;
	@Autowired
	IncreaseResourceService increaseResourceService;
	@Autowired
	IncreaseResourceSubService increaseResourceSubService;

	public void addResource(IncreaseResourceVo increaseResourceVo) throws Exception {
		IncreaseResource resource = new IncreaseResource();
		BeanUtils.copyProperties(increaseResourceVo, resource);
		String path = increaseResourceVo.getPath();
		String fileName = increaseResourceVo.getFileName();
		
		String cateId = increaseResourceVo.getCateId();
		if (StringUtils.isBlank(cateId)) {
			cateId = increaseResourceVo.getBookId();
		}
		int startSortNum = increaseResourceService.getStartNum(cateId);
		String resourceId = IdWorker.getIdStr();
		resource.setId(resourceId);
		resource.setCateId(cateId);
		resource.setPid(cateId);
		resource.setSortNum(startSortNum);
		resource.setIsSub(0);
		resource.setCreateBy(PMPHAppUtil.getCurrentUserEnName());
		resource.setUpdateBy(PMPHAppUtil.getCurrentUserEnName());
		resource.setUpdateTime(new Date());
		resource.setCreateTime(new Date());
		this.baseMapper.insert(resource);
		// 处理二维码相关
		increaseResourceService.saveQrCode(resourceId, increaseResourceVo.getQrCodeName());
		if (StringUtils.isNotBlank(path)) {
			fileHandler(path, fileName, resource);
		}
	}
	
	public void editResource(IncreaseResourceVo increaseResourceVo) throws Exception {
		String resourceId = increaseResourceVo.getId();
		IncreaseResource resource = new IncreaseResource();
		BeanUtils.copyProperties(increaseResourceVo, resource);
		String path = increaseResourceVo.getPath();
		String fileName = increaseResourceVo.getFileName();
		IncreaseResource oldResource = this.getById(resourceId);
		resource.setUpdateBy(PMPHAppUtil.getCurrentUserEnName());
		resource.setUpdateTime(new Date());
		if (StringUtils.isNotBlank(path) && !path.equals(oldResource.getPath())) {
			fileHandler(path, fileName, resource);
		}else {
			this.updateById(resource);
		}
		// 处理二维码相关
		increaseResourceService.saveQrCode(resourceId, increaseResourceVo.getQrCodeName());
	}

	public List<Map<String,String>> batchUploadResource(IncreaseResourceVo increaseResourceVo) {
		List<UploadFileVo> listFile = increaseResourceVo.getFileList();
		String bookId = increaseResourceVo.getBookId();
		String cateId = increaseResourceVo.getCateId();
		List<Map<String,String>> uploadMsg = new ArrayList<>();
		for(UploadFileVo fileVo:listFile) {
			Map<String,String> map = new HashMap<>();
			uploadMsg.add(map);
			try {
				String fileUrl = fileVo.getFileUrl();
				String originName = fileVo.getOriginName();
				map.put("fileName", originName);
				//判断文件类型，非视频、ppt、pdf直接入库，不用处理
				String fileName = getFileName(originName);
				IncreaseResource resource = getResourceByName(fileName, bookId, cateId);
				//如果获取到的资源没有，跳过
				if(resource==null ) {
					map.put("flag", "1");
					continue;
				}
				fileHandler(fileUrl,originName,resource);
			} catch (Exception e) {
				map.put("flag", "2");
				e.printStackTrace();
			}
			
		}
		return uploadMsg;
	}
	
	private void fileHandler(String fileUrl,String originName,IncreaseResource resource) {
		resource.setPath(fileUrl);
		String fileSuffix = getFileSuffix(originName);
		int resourceType = FfmpegUtil.getResourceType(fileSuffix);
		resource.setResourceType(resourceType);
		resource.setUpdateTime(new Date());
		//视频和ppt pdf都需要本地处理后，再上传至资源服务器，目前ppt和pdf处理一致
		if(resourceType==5) {
			// 当为ppt类型时，需要将ppt转为图片
			pptHandler(fileUrl,fileSuffix,resource);
		}else if(resourceType==6) {
			// 当为pdf类型时，也将pdf转为图片
			pdfHandler(fileUrl,fileSuffix,resource);
		}
		this.updateById(resource);
		if(resourceType==2) {
			videoHandler(fileUrl,fileSuffix,resource);
		}
	}
	
	private boolean videoHandler(String fileUrl,String fileSuffix,IncreaseResource resource) {
		// 进行视频压缩处理，原视频均认为是高清资源
		quartzManager.addJob(resource);
		return true;
	}
	
	private boolean pptHandler(String fileUrl,String fileSuffix,IncreaseResource resource) {
		String localFilePath = ResourceServerUtils.resourceFileDownload(fileUrl);
		if(StringUtils.isBlank(localFilePath)) {
			return false;
		}
		// 当为pdf类型时，将pdf转为图片
		PptToImg.convertPptToImg(localFilePath);
		pptpdfImgHandler(localFilePath,resource);
		return true;
	}
	
	private boolean pdfHandler(String fileUrl,String fileSuffix,IncreaseResource resource) {
		String localFilePath = ResourceServerUtils.resourceFileDownload(fileUrl);
		if(StringUtils.isBlank(localFilePath)) {
			return false;
		}
		// 当为pdf类型时，将pdf转为图片
		PptToImg.pdfToImg(localFilePath);
		pptpdfImgHandler(localFilePath,resource);
		return true;
	}
	
	private void pptpdfImgHandler(String localFilePath,IncreaseResource resource) {
		String imgPptPath = localFilePath.substring(0, localFilePath.lastIndexOf("."));
		File file = new File(imgPptPath);
		if (file.exists() && file.isDirectory()) {
			int imgCount = file.list().length;
			resource.setPptPages(imgCount);
			//将生成的图片上传到资源服务器
			for (int i = 1; i <= imgCount; i++) {
				File imgFile = new File(imgPptPath+"/"+i+".png");
				if(imgFile.exists()) {
					String url = ResourceServerUtils.uploadFile(imgFile.getAbsolutePath());
					if(StringUtils.isNotBlank(url)) {
						saveResourceSub(url,i,resource.getId());
					}
				}
			}
		}
	}
	
	private void saveResourceSub(String url,int sortNum,String resourceId) {
		IncreaseResourceSub sub = new IncreaseResourceSub();
		sub.setId(IdWorker.getIdStr());
		sub.setImgPath(url);
		sub.setSortNum(sortNum);
		sub.setResourceId(resourceId);
		increaseResourceSubService.save(sub);
	}
	

	
	private IncreaseResource getResourceByName(String name, String bookId, String categoryId) {
		QueryWrapper<IncreaseResource> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("book_id", bookId);
		if (StringUtils.isNotBlank(categoryId)) {
			queryWrapper.eq("cate_id", categoryId);
		}
		queryWrapper.eq("file_name", name);
		List<IncreaseResource> list = this.baseMapper.selectList(queryWrapper);
		if(list!=null && list.size()>0) {
			return list.get(0);
		}
		return null;
	}
	
	private String getFileName(String fileName) {
		return fileName.substring(0, fileName.lastIndexOf("."));
	}

	private String getFileSuffix(String fileName) {
		return fileName.substring(fileName.lastIndexOf("."));
	}
	
	private String getFileSize(long fileSize) {
		long size = fileSize / 1024 / 1024;
		String sizeStr = size+"MB";
		if(size<1) {
			sizeStr = fileSize / 1024+"KB";
		}
		return sizeStr;
	}

	public static void main(String[] args) {
		String a = "d:/aa/";
		File file = new File(a);
		System.out.println(file.getAbsolutePath());
	}
}
